import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import GUI from 'three/examples/jsm/libs/lil-gui.module.min.js';
import TWEEN from 'tween.ts';

const DefaultCanvasWidth = 800;
const DefaultCanvasHeight = 600;
export const gui = new GUI();

export const scene = new THREE.Scene();
let camera: any;
export const getCamera = () => {
    return camera;
}

export const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(DefaultCanvasWidth, DefaultCanvasHeight);
let controls: any;

export const usePerCamera = () => {
    scene.remove(camera);
    camera = new THREE.PerspectiveCamera(75, DefaultCanvasWidth / DefaultCanvasHeight, 0.1, 1000); // 默认使用透视相机
    camera.position.set(300, 300, 300);
    camera.lookAt(0, 0, 0);
    scene.add(camera);
    controls && (controls.object = camera);
}

export const useOrthCamera = () => {
    scene.remove(camera);
    camera = new THREE.OrthographicCamera(-DefaultCanvasWidth / 1.5, DefaultCanvasWidth / 1.5, DefaultCanvasHeight / 1.5, -DefaultCanvasHeight / 1.5, 1, 8000);
    camera.position.set(300, 300, 300);
    camera.lookAt(0, 0, 0);
    scene.add(camera);
    controls && (controls.object = camera);
}

usePerCamera(); // 默认使用透视相机
controls = new OrbitControls(camera, renderer.domElement);
controls.addEventListener('change', function () {
    // 浏览器控制台查看相机位置变化
    // console.log('camera.position',camera.position);
});

export {controls};

export const size = new THREE.Vector2();

export const init = (domRef: any) => {
    setTimeout(() => {
        domRef.value.appendChild(renderer.domElement);
    });
    renderer.getSize(size);
}

const GlobalAnimates: Function[] = [];

export const addLoops = (...animates: any[]) => {
    GlobalAnimates.push.apply(GlobalAnimates, animates);
}

function loop(time: number) {
    TWEEN.update(time);
    for (const animate of GlobalAnimates) {
        animate();
    }
    renderer.render(scene, camera);
    requestAnimationFrame(loop);
}
requestAnimationFrame(loop)

export const resize = (width: number, height: number) => {
    renderer.setSize(width, height);
    renderer.getSize(size);
    if (camera.aspect) {
        camera.aspect = width / height;
    }
    camera.updateProjectionMatrix();
}